package com.beimi.game.rule;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.beimi.game.MJService;
import com.beimi.game.MajiongGame;
import com.beimi.game.action.IAction;
import com.beimi.game.module.GameCardModule;
import com.beimi.game.module.GamePlayerModule;
import com.beimi.game.module.GameTurnModule;
import com.beimi.game.module.GameUserCmdModule;
import com.beimi.game.player.GamePlayer;

public class MajiangRule extends Rule {

	private MajiongGame game;
	
	private MJService service;

	public void deal() {
		// 每人13张 一共 13*4 ＝ 52张 庄家多一张 53张
		GamePlayer[] players = game.getModule(GamePlayerModule.class).getPlayers();
		int seatIndex = game.getDealer();
		for (int i = 0; i < 52; ++i) {
			int card = game.getModule(GameCardModule.class).pop();
			players[seatIndex++].getCardModule().addMajong(card);
			seatIndex++;
			seatIndex %= 4;
		}

		// 庄家多摸最后一张
		int card = game.getModule(GameCardModule.class).pop();
		players[game.getDealer()].getCardModule().addMajong(card);
		// 当前轮设置为庄家
		// game.turn = game.button;
	}

	public MajiongGame getGame() {
		return game;
	}

	public void setGame(MajiongGame game) {
		this.game = game;
		service = new MJService();
		service.setGame(game);
	}

	public void addAI() {
		for (int i = game.getModule(GamePlayerModule.class).getNumPlayer(); i < 4; ++i) {
			GamePlayer player = new GamePlayer();
			player.init();
			game.getModule(GamePlayerModule.class).addPlayer(player);
		}
	}

	@Override
	public void run() {
		try {
			switch (game.getState()) {
			case 0:
				begin();
				game.setState(1);
				break;

			case 1:
				play();
				break;

			case 2:

				break;
			}
		} catch (Exception e) {
			LOG.error("", e);
			game.setState(2);
		}

	}

	private void play() {
		List<IAction> actions = game.getModule(GameUserCmdModule.class).getCommands();
		List<IAction> list = new ArrayList<>();
		for (IAction action : actions) {
			action.execute(service);
			if (!action.isFinished()) {
				list.add(action);
			}
		}
		
		game.getModule(GameUserCmdModule.class).setComands(list);
	}

	private void begin() {
		game.getModule(GameCardModule.class).initMajiong();
		deal();

		GamePlayer[] players = game.getModule(GamePlayerModule.class).getPlayers();
		for (int i = 0; i < players.length; ++i) {
			// 开局时，通知前端必要的数据
			GamePlayer player = players[i];
			// 通知玩家手牌
			player.sendMessage("game_holds_push", JSON.toJSONString(player.getCardModule()));
			player.sendMessage("game_begin_push",
					game.getModule(GameTurnModule.class).getCurrentTurn());
			// userMgr.sendMsg(s.userId,'game_begin_push',game.button);
			//
			// if(huansanzhang == true){
			// game.state = "huanpai";
			// //通知准备换牌
			// userMgr.sendMsg(s.userId,'game_huanpai_push');
			// }
			// else{
			// game.state = "dingque";
			// //通知准备定缺
			// userMgr.sendMsg(s.userId,'game_dingque_push');
			// }
		}
		
		service.doUserMoPai();
	}
}
